<script setup>
import { reactive, ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getCategoryListApi, deleteCategoryApi } from '../../service/goods.js';
import CategoryAdd from './components/category-add.vue';
import CategoryUpdate from './components/category-update.vue';

const state = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 15,
  query: {
    keyword: '',
    pagination: {
      page: 1,
      limit: 15,
    },
  },
  list: [],
});

const categoryAddRef = ref(null);
const categoryUpdateRef = ref(null);

const showCreateView = () => {
  categoryAddRef.value.showDrawer();
};

const showUpdateView = (row) => {
  categoryUpdateRef.value.showDrawer(row);
};

const fetchList = async () => {
  try {
    const res = await getCategoryListApi(state.query);
    if (res.code === 200) {
      state.list = res.data.list;
      state.total = res.data.total;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error('加载列表数据失败');
  }
};

const handleSearch = () => {
  state.currentPage = 1;
  fetchList();
};

const doDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定删除当前分类?', 'Warning', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    });
    const res = await deleteCategoryApi(row);
    if (res.code === 200) {
      ElMessage.success(res.msg);
      fetchList();
    } else {
      ElMessage.error(res.msg);
    }
  } catch {


  }
};

onMounted(() => {
  fetchList();
});
</script>

<template>
  <el-main>
    <div class="toolbar">
      <el-button type="danger" @click="showCreateView">新增分类</el-button>
      <el-input v-model="state.query.keyword" placeholder="分类名称" @keyup.enter="handleSearch"/>
      <el-button type="primary" icon="search" @click="handleSearch">搜索</el-button>
    </div>
    <el-table :data="state.list" style="width: 100%" border>
      <el-table-column prop="id" label="ID" width="180"/>
      <el-table-column prop="title" label="分类名称"/>
      <el-table-column prop="sort" label="排序"/>
      <el-table-column prop="create_time" label="创建时间"/>
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" size="small" @click="showUpdateView(row)">编辑</el-button>
          <el-button type="danger" size="small" @click="doDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <category-add ref="categoryAddRef" @reload="fetchList"/>
    <category-update ref="categoryUpdateRef" @reload="fetchList"/>
  </el-main>
</template>
